package com.ysl.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

public class TcpClientHandler extends ChannelInboundHandlerAdapter {


    /**
     * 循环次数
     */
    private AtomicInteger fcount = new AtomicInteger(1);

    /**
     * 建立连接时
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = ipSocket.getPort();
        String host = ipSocket.getHostString();
        System.out.println("服务端建立连接port==========" + port);

        ctx.fireChannelActive();
    }

    /**
     * 关闭连接时
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = ipSocket.getPort();
        String host = ipSocket.getHostString();
        System.out.println("服务端断开连接=====" + port);
        final EventLoop eventLoop = ctx.channel().eventLoop();
        //断线重连
        Bootstrap bootstrap = TcpManyClient.getBootstrap(eventLoop);
        TcpManyClient.doConnect(bootstrap,host,port);
        super.channelInactive(ctx);

    }

    /**
     * 心跳请求处理 每30秒发送一次心跳请求;
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
//		System.out.println("循环请求的时间：" + new Date() + "，次数" + fcount.get());
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = ipSocket.getPort();
        String host = ipSocket.getHostString();
        System.out.println("发送心跳给服务端=====" + port);
        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj;
            // 如果写通道处于空闲状态,就发送心跳命令
            if (IdleState.WRITER_IDLE.equals(event.state())) {
                String msg = "2222";
                byte[] content = msg.getBytes();
                // 要发送信息的长度
                int contentLength = content.length;
                //SmartCarProtocol protocol = new SmartCarProtocol(contentLength, content);
                //ctx.channel().writeAndFlush(protocol);
                fcount.getAndIncrement();
            }
        }
    }

    /**
     * 业务逻辑处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        int port = ipSocket.getPort();
        String host = ipSocket.getHostString();
        //SmartCarProtocol body = (SmartCarProtocol) msg;
        //System.out.println("Client接受的服务端信息" + port + " :" + new String(body.getContent()));

    }

}
